package com.hjt.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hjt.common.to.es.SkuEsModel;
import com.hjt.gulimall.search.config.ElasticConfig;
import com.hjt.gulimall.search.constant.EsConstant;
import com.hjt.gulimall.search.service.MallSearchService;
import com.hjt.gulimall.search.vo.SearchParam;
import com.hjt.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author:97007
 * @date:2021/9/24 19:09
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {


    @Autowired
    private RestHighLevelClient restClient;

    @Override
    public SearchResult search(SearchParam searchParam) {
        // 1.准备检索请求
        SearchRequest request = buildSearchRequest(searchParam);
        SearchResult result = null;

        try {
            // 2.执行检索请求
            SearchResponse response = restClient.search(request, ElasticConfig.COMMON_OPTIONS);

            // 3.分析响应数据，封装成需要的数据
            result = buildSearchResponse(response, searchParam);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return result;
    }

    /**
     * 构建检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        // 1.设置检索的索引
        SearchRequest request =  new SearchRequest(EsConstant.PRODUCT_INDEX);

        // 2.构建检索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 模糊匹配、过滤（属性、分类、品牌、价格区间、是否有库存）
         */
        // 2.1 构建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.1.1 must 模糊匹配
        if (StringUtils.hasLength(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        // 2.1.2 构建filter
        // 分类
        if (searchParam.getCatelogId() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatelogId()));
        }
        // 品牌
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        // 是否有库存
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        // 价格区间
        if (StringUtils.hasLength(searchParam.getSkuPrice())) {
            String[] s = searchParam.getSkuPrice().split("_");
            RangeQueryBuilder skuPriceRange = QueryBuilders.rangeQuery("skuPrice");
            if (searchParam.getSkuPrice().startsWith("_")) {
                skuPriceRange.gte("0").lte(s[1]);
            } else if(searchParam.getSkuPrice().endsWith("_")) {
                skuPriceRange.gte(s[0]);
            } else{
                skuPriceRange.gte(s[0]).lte(s[1]);
            }
            boolQuery.filter(skuPriceRange);
        }
        // 属性
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            List<String> attrs = searchParam.getAttrs();
            // attrs=1_5寸:6寸&attrs=1_5寸:6寸
            for (String attr : attrs) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                // 属性id
                String attrId = s[0];
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                // 属性的值
                String[] attrValues = s[1].split(":");
                // 每一个属性条件都得生成nestedQuery
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                boolQuery.filter(QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None));
            }
        }
        // 封装query条件
        sourceBuilder.query(boolQuery);

        /*
        排序、分页、高亮
         */
        // 2.2.1排序
        if (StringUtils.hasLength(searchParam.getSort())) {
            String[] s = searchParam.getSort().split("_");
            sourceBuilder.sort(s[0], s[1].equalsIgnoreCase("asc") ?SortOrder.ASC:SortOrder.DESC);
        }
        // 2.2.2分页
        if (searchParam.getPageNum() != null) {
            int from = (searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE;;
            sourceBuilder.from(from);
            sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        }
        // 2.2.3高亮
        if (StringUtils.hasLength(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /*
        聚合分析
         */
        // 2.3.1品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId").size(50);
        // 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1)); // 名字
        brandAgg.subAggregation(AggregationBuilders.terms("brandImageAgg").field("brandImg").size(1)); // 图片
        sourceBuilder.aggregation(brandAgg);

        // 2.3.2分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(50);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        // 2.3.3属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attrAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        attrAgg.subAggregation(attrIdAgg);
        // 聚合attrId对应的所有名字和属性值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(50));
        sourceBuilder.aggregation(attrAgg);

        // 3.设置检索条件
        request.source(sourceBuilder);
        System.out.println("DSL:" + sourceBuilder);
        return request;
    }


    /**
     * 分析响应数据，封装成需要的数据
     * @return
     */
    private SearchResult buildSearchResponse(SearchResponse response, SearchParam searchParam) {
        SearchResult result = new SearchResult();

        // 1.商品信息
        if (response.getHits() != null) {
            SearchHit[] hits = response.getHits().getHits();
            if (hits.length > 0) {
                List<SkuEsModel> skuEsModelList = new ArrayList<>(hits.length);
                for (SearchHit hit : hits) {
                    String jsonString = hit.getSourceAsString();
                    SkuEsModel skuEsModel = JSON.parseObject(jsonString, SkuEsModel.class);
                    skuEsModelList.add(skuEsModel);
                    //  关键字检索，则标题有高亮
                    if (StringUtils.hasLength(searchParam.getKeyword())) {
                        HighlightField skuTitleHighLight = hit.getHighlightFields().get("skuTitle");
                        String string = skuTitleHighLight.getFragments()[0].string();
                        skuEsModel.setSkuTitle(string);
                    }
                }
                result.setProducts(skuEsModelList);
            }
        }
        // ============聚合信息==============
        Aggregations aggregations = response.getAggregations();

        // 2.属性信息
        ParsedNested attrAgg = aggregations.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attrIdAgg.getBuckets();
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>(attrIdAggBuckets.size());
        Map<Long,String> attrNameMap = new HashMap<>(attrIdAggBuckets.size()); // 属性id-属性名，用于第6步面包屑封装，根据id查属性名字
        for (Terms.Bucket attrBucket : attrIdAggBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 2.1 属性id
            attrVo.setAttrId(Long.parseLong(attrBucket.getKeyAsString()));
            // 2.2 属性名字
            String attrName = ((ParsedStringTerms) attrBucket.getAggregations().get("attrNameAgg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            attrNameMap.put(attrVo.getAttrId(), attrVo.getAttrName());
            // 2.3 属性值
            List<? extends Terms.Bucket> attrValueAgg = ((ParsedStringTerms) attrBucket.getAggregations().get("attrValueAgg")).getBuckets();
            List<String> attrVoValueList = new ArrayList<>(attrValueAgg.size());
            for (Terms.Bucket bucket : attrValueAgg) {
                attrVoValueList.add(bucket.getKeyAsString());
            }
            attrVo.setAttrValue(attrVoValueList);
            attrVoList.add(attrVo);
        }
        result.setAttrs(attrVoList);

        // 3.品牌信息
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        Map<Long, String> brandNameMap = new HashMap<>(brandAggBuckets.size());
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>(brandAggBuckets.size());
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 3.1 品牌id
            String brandId = brandAggBucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            // 3.2 品牌名称
            String brandName = ((ParsedStringTerms) brandAggBucket.getAggregations().get("brandNameAgg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandNameMap.put(brandVo.getBrandId(), brandName);
            // 3.3 品牌logo图片
            String brandImg = ((ParsedStringTerms) brandAggBucket.getAggregations().get("brandImageAgg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVoList.add(brandVo);
        }
        result.setBrands(brandVoList);

        // 4.分类信息
        ParsedLongTerms catalogAgg = aggregations.get("catalogAgg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>(buckets.size());
        for (Terms.Bucket bucket : buckets) {
            // 4.1 分类id
            String catalogIdString = bucket.getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(Long.parseLong(catalogIdString));
            // 4.2 分类名字
            ParsedStringTerms bucket2 = bucket.getAggregations().get("catalogNameAgg");
            String catalogName = bucket2.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVoList.add(catalogVo);
        }
        result.setCatalogs(catalogVoList);

        // 5.分页信息
        // 5.1总记录数
        long total = response.getHits().getTotalHits().value;
        result.setTotal(total);
        // 5.2总页码
        int totalPages = (int) (total % EsConstant.PRODUCT_PAGE_SIZE == 0 ? total/EsConstant.PRODUCT_PAGE_SIZE : total/EsConstant.PRODUCT_PAGE_SIZE + 1);
        result.setTotalPages(totalPages);
        // 5.3当前页码
        result.setPageNum(searchParam.getPageNum());

        // 6.1面包屑导航条(属性)
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            ArrayList<Long> attrIds = new ArrayList<>();
            List<SearchResult.NavVo> navVoList = searchParam.getAttrs().stream().map(attrParam -> {
                String[] s = attrParam.split("_");
                Long attrId = Long.parseLong(s[0]); // 属性id
                attrIds.add(attrId);
                String attrValue = s[1];
                String attrName = attrNameMap.get(attrId); // 属性名
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName(attrName); // 面包屑名称
                navVo.setNavValue(attrValue); // 面包屑的值
                // 取消面包屑后跳转的url，即将面包屑对应的查询参数去除即可
                // 1.从原生查询参数中删除对应的查询参数
                String queryString = searchParam.get_queryString();
                try {
                    queryString =  URLDecoder.decode(queryString, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String query = queryString.replaceAll("(&?attrs="+attrParam+"&?)", "");
                navVo.setLink("http://search.gulimall.com/list.html?"+query);
                return navVo;
            }).collect(Collectors.toList());
            result.getNavVoList().addAll(navVoList);
            result.setAttrIdList(attrIds);
        }
        // 6.2品牌面包屑导航
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            List<SearchResult.NavVo> navVoList = searchParam.getBrandId().stream().map(brandId -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName("品牌");
                navVo.setNavValue(brandNameMap.get(brandId));
                // 取消面包屑后跳转的url，即将面包屑对应的查询参数去除即可
                // 1.从原生查询参数中删除对应的查询参数
                String queryString = searchParam.get_queryString();
                try {
                    queryString =  URLDecoder.decode(queryString, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String query = queryString.replaceAll("(&?brandId="+brandId+"&?)", "");
                navVo.setLink("http://search.gulimall.com/list.html?"+query);
                return navVo;
            }).collect(Collectors.toList());
            result.getNavVoList().addAll(navVoList);
        }

        return result;
    }


}
